from flask import Blueprint, request
from apps.common.query_wrap import QueryFilter
from apps.common.result import table,success
from apps.common.validate import xss_escape
from apps.models.crawler_entity import CrawlerEntity, CrawlerPageOut, CrawlerSaveIn
from apps.common.db_help import model_to_dicts

crawler_bp = Blueprint('Crawler', __name__, url_prefix='/crawler')


@crawler_bp.route('/page', methods=['post'])
def page():
    # 获取请求参数
    role_name = xss_escape(request.args.get('roleName', type=str))
    role_code = xss_escape(request.args.get('roleCode', type=str))
    # 查询参数构造
    mf = QueryFilter()
    if role_name:
        mf.vague(field_name="name", value=role_name)
    if role_code:
        mf.vague(field_name="code", value=role_code)
    mf.exact(field_name="deleted", value=0)
    # orm查询
    # 使用分页获取data需要.items
    role = CrawlerEntity.query.filter(mf.get_filter(CrawlerEntity)).layui_paginate()
    count = role.total
    # 返回api
    return table(data=model_to_dicts(schema=CrawlerPageOut, data=role.items), count=count)


@crawler_bp.route('/save', methods=['post'])
def save():
    json = request.json
    crawlerSaveIn = CrawlerEntity(
        id=xss_escape(json.get("id")),
        name=xss_escape(json.get("name")),
        sleep_time=xss_escape(json.get("sleep_time")),
        use_proxy=xss_escape(json.get("use_proxy")),
        user_agent=xss_escape(json.get("user_agent")),
        list_config=xss_escape(json.get("list_config")),
        detail_config=xss_escape(json.get("detail_config")),
        db_config=xss_escape(json.get("db_config")),
        render_type=xss_escape(json.get("render_type")),
        web_site=xss_escape(json.get("web_site"))
    )
    if crawlerSaveIn.id:
        delattr(crawlerSaveIn, "_sa_instance_state")
        CrawlerEntity.query.filter_by(id=crawlerSaveIn.id).update(crawlerSaveIn.__dict__)
    else:
        CrawlerEntity().save(crawlerSaveIn)
    return success()


@crawler_bp.delete('/<id>')
def del_crawler(id: int):
    CrawlerEntity.query.filter_by(id=id).update({
        "deleted": 1
    })
    return success()